<template>
  <el-container style="height: 100vh;">
    <el-main style="display: flex; justify-content: center; align-items: center; background-color: #f5f7fa;">
      <el-card :body-style="{ padding: '20px' }" style="width: 400px; border-radius: 10px;">
        <h2 style="text-align: center; margin-bottom: 20px;">职工管理系统登录</h2>

        <el-form :model="form" ref="formRef" status-icon label-position="top">
          <el-form-item label="用户名" prop="empName" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
            <el-input v-model="form.empName" placeholder="请输入用户名" />
          </el-form-item>

          <el-form-item label="密码" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
            <el-input v-model="form.password" type="password" placeholder="请输入密码" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" block @click="handleLogin" :loading="loading">登录</el-button>
          </el-form-item>
        </el-form>

        <div v-if="errorMessage" style="color: red; text-align: center; margin-top: 10px;">
          {{ errorMessage }}
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script>
import { ref } from 'vue';
import { login } from '@/api/api'; // 引入封装的登录接口
import { useRouter } from 'vue-router';

export default {
  setup() {
    const router = useRouter();
    const form = ref({
      empName: '',
      password: '',
    });
    const loading = ref(false); // 控制按钮加载状态
    const errorMessage = ref(''); // 错误信息

    // 登录处理函数
    const handleLogin = async () => {
      errorMessage.value = ''; // 清空错误信息
      loading.value = true; // 设置按钮为加载状态
      console.log(form.value);

      try {
        const response = await login(
            form.value.empName,
            form.value.password,
        );
        if (response.data.code === 0) {
          // 登录成功，存储token并跳转到首页
          localStorage.setItem('token', response.data.data.token);
          console.log(response.data.data);
          router.push('/books'); // 登录成功后重定向到首页
        } else {
          // 登录失败，显示错误信息
          errorMessage.value = '用户名或密码错误';
        }
      } catch (error) {
        // 捕获异常并显示错误信息
        errorMessage.value = '登录失败，请重试';
      } finally {
        loading.value = false; // 登录完成后恢复按钮状态
      }
    };

    return {
      form,
      handleLogin,
      loading,
      errorMessage,
    };
  },
};
</script>

<style scoped>
.el-container {
  background-color: #f5f7fa;
}

.el-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
